package org.example.paymentservice.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.paymentservice.config.PaymentProperties;
import org.example.paymentservice.entity.Order;
import org.example.paymentservice.service.OrderProcessor;
import org.example.paymentservice.service.PaymentService;
import org.example.paymentservice.service.WebhookHandler;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service("alipay_webhook")
@RequiredArgsConstructor
public class AliPayWebhookHandler implements WebhookHandler {
    private final PaymentProperties paymentProperties;
    private final PaymentService paymentService;
    private final OrderProcessor orderProcessor;

    @Override
    public void handlePaymentNotification(String payload, Map<String, String> params) {
        try {
            if (verifySignature(payload, params.get("sign"))) {
                String tradeStatus = params.get("trade_status");
                String transactionId = params.get("out_trade_no");
                
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 支付成功，更新订单状态
                    paymentService.validatePayment(transactionId);
                    log.info("AliPay payment notification processed successfully for transaction: {}", transactionId);
                } else if ("TRADE_CLOSED".equals(tradeStatus)) {
                    // 交易关闭
                    orderProcessor.updateOrderStatus(
                        Long.valueOf(transactionId), 
                        Order.PaymentStatus.FAILED
                    );
                    log.info("AliPay payment closed for transaction: {}", transactionId);
                }
            } else {
                log.error("Invalid signature for AliPay notification");
            }
        } catch (Exception e) {
            log.error("Error processing AliPay notification", e);
            throw new RuntimeException("Failed to process payment notification", e);
        }
    }

    @Override
    public void handleRefundNotification(String payload, Map<String, String> params) {
        try {
            if (verifySignature(payload, params.get("sign"))) {
                String refundStatus = params.get("refund_status");
                String transactionId = params.get("out_trade_no");
                
                if ("REFUND_SUCCESS".equals(refundStatus)) {
                    // 退款成功，更新订单状态
                    orderProcessor.updateOrderStatus(
                        Long.valueOf(transactionId), 
                        Order.PaymentStatus.REFUNDED
                    );
                    log.info("AliPay refund notification processed successfully for transaction: {}", transactionId);
                }
            } else {
                log.error("Invalid signature for AliPay refund notification");
            }
        } catch (Exception e) {
            log.error("Error processing AliPay refund notification", e);
            throw new RuntimeException("Failed to process refund notification", e);
        }
    }

    @Override
    public boolean verifySignature(String payload, String signature) {
        try {
            return AlipaySignature.rsaCheckV1(
                payload,
                signature,
                paymentProperties.getAliPay().getPublicKey(),
                "UTF-8"
            );
        } catch (AlipayApiException e) {
            log.error("Error verifying AliPay signature", e);
            return false;
        }
    }
}